import * as phaser from "phaser";
import {RatingSystem} from "../sys/rating.ts";

/**
 * 鱼鱼
 */
export class Fish extends phaser.Physics.Arcade.Sprite {

    id: number = -1;
    private readonly left: boolean = false;
    private rating: RatingSystem;
    private startTime: number = 0;

    constructor(scene: phaser.Scene, rating: RatingSystem) {
        const index = Math.floor(Math.random() * 10);
        const left = index == 0 || index == 6 || index == 7 || index == 9;
        const {width, height} = scene.cameras.main;
        let x = left ? width + 20 : -20;
        let y = phaser.Math.Between(height - 150, height - 160);
        let texture = 'SpritesFishRight';
        if (phaser.Math.Between(0, 1) == 0) {
            texture = 'SpritesFishError'
        }
        super(scene, x, y, texture, `target${index}`);
        scene.add.existing(this);
        scene.physics.add.existing(this);
        this.setInteractive();
        this.setScale(1.4, 1.4);
        this.rating = rating;
        this.id = index;
        this.left = left;
        this.addEvent();
    }

    addEvent() {
        this.on("pointerdown", () => {
            if (this.scene.sys.game.isPaused) return;

            this.disableBody(true, true);
            let texture: string;
            if (this.texture.key == 'SpritesFishRight') {
                // 点击红色鱼，反应成功
                this.rating.reactionRight(RatingSystem.FISH);
                texture = "TextRight";
                this.rating.onTimer(Math.floor(this.scene.time.now - this.startTime));
            } else {
                // 点击黄色鱼，抑制失败
                this.rating.restrainError();
                texture = "TextError";
            }
            let text = this.scene.add.sprite(this.x, this.y - 20, texture)
                .setOrigin(0.5)
                .setScale(0.8)
            this.scene.time.delayedCall(500, () => {
                text.destroy(true);
            });
            this.exit();
        }, this);
    }

    /**
     * 开始游
     */
    start(velocity: number) {
        this.setVelocityX(this.left ? -velocity : velocity);
        // 开始时，需要等鱼儿完全出现才算时间，这里简单+300处理一下
        this.startTime = this.scene.time.now + 300;
    }

    preUpdate(time: number, delta: number) {
        super.preUpdate(time, delta);
        let {width} = this.scene.cameras.main;
        if (this.x >= width + 20 || this.x < -20) {
            // 红色鱼没点击，反应失败
            if (this.texture.key == 'SpritesFishRight') {
                this.rating.reactionError();
            } else if (this.texture.key == 'SpritesFishError') { // 黄色鱼没点击，抑制成功
                this.rating.restrainRight();
            }
            this.exit();
        }
    }

    private exit() {
        this.disableBody(true, true);
        this.destroy(true);
        if (this.body) {
            this.scene.physics.world.remove(this.body);
        }
    }
}